package com.youle.robots.gateway.config;

import com.youle.robots.gateway.api.InterceptorExcption;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 * 授权拦截器
 * User: kedong
 * Date: 18-3-20
 * Time: 上午10:04
 * To change this template use File | Settings | File and Code Templates ->Includes->File Header.
 */
@Slf4j
@Component
public class AuthorizeInterceptor implements HandlerInterceptor {

    private final String TOKEN = "x-access-token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        String token = request.getHeader(TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new InterceptorExcption(String.format("[%s] must be not empty!", TOKEN), HttpStatus.BAD_REQUEST);
        }

        log.info(TOKEN + ": " + token);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) {

    }
}
